<template>
    <el-drawer v-model="showDrawer" :direction="'rtl'" size="30%">
        <template #header>
            <h4>文章设置</h4>
        </template>
        <template #default>
            <el-form ref="dialogFormRef" :model="state.form" :rules="state.rules" label-width="120px"
                     size="default">
                <el-row>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt20 pr20">
                        <el-form-item label="标题" prop="title">
                            <el-input v-model="state.form.title" clearable
                                      placeholder="请输入文章标题"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt20 pr20">
                        <el-form-item label="别名" prop="alias">
                            <el-input v-model="state.form.alias" clearable
                                      placeholder="请输入文章别名">
                                <template #append>
                                    <el-button @click="refreshAlias" :icon="Refresh"></el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt20 pr20">
                        <el-form-item label="摘要" prop="abstractContent">
                            <el-input v-model="state.form.abstractContent" clearable
                                      type="textarea"
                                      placeholder="请输入文章别名"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt20 pr20">
                        <el-form-item label="标签列表" prop="tagNames">
                            <el-select-v2
                                value-key="value"
                                v-model="state.form.tagNames"
                                filterable
                                :reserve-keyword="false"
                                allow-create
                                multiple
                                remote
                                :remote-method="searchTags"
                                :options="tagOptions"
                                placeholder="请选择标签"
                                class="w100"
                                :loading="searchTagLoading"
                            >
                                <template #default="{item}">
                                    {{ item.label }}
                                </template>
                            </el-select-v2>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt20 pr20">
                        <el-form-item label="分类列表" prop="categoryNames">
                            <el-select-v2
                                value-key="value"
                                v-model="state.form.categoryNames"
                                filterable
                                :reserve-keyword="false"
                                allow-create
                                multiple
                                remote
                                :remote-method="searchCategories"
                                :options="categoryOptions"
                                placeholder="请选择分类"
                                class="w100"
                                :loading="searchCategoryLoading"
                            >
                                <template #default="{item}">
                                    {{ item.label }}
                                </template>
                            </el-select-v2>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt20 pr20">
                        <el-form-item label="封面" prop="coverUrl">
                            <el-input v-model="state.form.coverUrl" clearable
                                      type="textarea"
                                      placeholder="请输入封面地址"/>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt20 pr20">
                        <el-form-item label="发布时间" prop="publishTime">
                            <el-date-picker
                                v-model="state.form.publishTime"
                                type="datetime"
                                placeholder="请选择发布时间"
                                format="YYYY/MM/DD HH:mm:ss"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt20 pr20">
                        <el-form-item label="是否置顶" prop="publishTime">
                            <el-checkbox v-model="state.form.sort"
                                         label="置顶"
                                         :true-label="1"
                                         :false-label="0"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto" class="mt20 mb20 pr20">
                <el-button size="default" @click="cancelSetting">取 消</el-button>
                <el-button size="default" type="info" @click="confirmClick(1)">保 存</el-button>
                <el-button size="default" type="primary" @click="confirmClick(2)">发 布</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue'
import {tagApi} from "/@/api/tag";
import stores from "/@/stores";
import {Refresh} from "@element-plus/icons-vue";
import {articleApi} from "/@/api/article";
import {categoryApi} from "/@/api/category";
import {commonApi} from "/@/api/common";

const emit = defineEmits(['confirm', 'cancel']);
const dialogFormRef = ref();
const state = reactive<DialogState<ArticleSetting>>({
    dialog: {
        show: true
    },
    form: {
        abstractContent: "",
        alias: "",
        categoryNames: [],
        coverUrl: "",
        metadata: {},
        publishTime: new Date(),
        sort: 0,
        status: 1,
        tagNames: [],
        title: "",
    },
    rules: {
        "name": [{required: true, message: "请输入存储策略名", trigger: 'blur'}],
        "title": [{required: true, message: "请输入文章标题", trigger: 'blur'}],
        "alias": [{required: true, message: "请输入文章别名", trigger: 'blur'}],
    }
})

interface Option {
    label: string;
    value: string;
}

const tagOptions = ref<Array<Option>>([])
const searchTagLoading = ref(false);
const searchTags = async (keyword: string) => {
    searchTagLoading.value = true;
    const pageResult = await tagApi.listTag({
        name: keyword
    });
    tagOptions.value = pageResult.records.map(tag => {
        return {
            label: tag.name,
            value: tag.name
        }
    });
    searchTagLoading.value = false;
};

const categoryOptions = ref<Array<Option>>([])
const searchCategoryLoading = ref(false);
const searchCategories = async (keyword: string) => {
    searchCategoryLoading.value = true;
    const pageResult = await categoryApi.listCategory({
        name: keyword
    });
    categoryOptions.value = pageResult.records.map(category => {
        return {
            label: category.name,
            value: category.name
        }
    });
    searchCategoryLoading.value = false;
};

const showDrawer = ref(false)
const openDrawer = async (articleVo: ArticleVo) => {
    const tagList = await tagApi.listTag();
    tagOptions.value = tagList.records.map(tag => {
        return {
            label: tag.name,
            value: tag.name
        }
    });
    const categoryList = await categoryApi.listCategory();
    categoryOptions.value = categoryList.records.map(category => {
        return {
            label: category.name,
            value: category.name
        }
    });
    const categoryNames: Array<string> = articleVo.categoryList.map(category => category.name);
    const tagNames: Array<string> = articleVo.blogTagList.map(tag => tag.name)
    state.form = {
        tagNames: tagNames,
        categoryNames: categoryNames,
        ...articleVo
    }
    if (!state.form.publishTime) {
        state.form.publishTime = new Date();
    }
    showDrawer.value = true;
};
const cancelSetting = () => {
    closeDrawer();
    emit("cancel")
}
const closeDrawer = () => {
    showDrawer.value = false
    dialogFormRef.value.resetFields()
}
const refreshAlias = async () => {
    state.form.alias = await commonApi.alias(state.form.title)
    dialogFormRef.value.validateField("alias");
}
const confirmClick = (status: 1 | 2 = 1) => {
    state.form.status = status;
    dialogFormRef.value?.validate((isValid: boolean) => {
            if (isValid) {
                stores.commonStoreState.openLoading()
                articleApi.setting(state.form).then(() => {
                    closeDrawer();
                    emit("confirm")
                    dialogFormRef.value?.resetFields();
                }).finally(() => {
                    stores.commonStoreState.closeLoading()
                })
            }
        }
    );
}

defineExpose({
    openDrawer,
    closeDrawer
})
</script>
